package com.otaku.config;

import com.otaku.exception.TipException;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;

import javax.xml.ws.Response;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 标题：ControllerConfig<br>
 * 功能说明：控制器配置：包含全局控制器异常处理、数据绑定/移除<br>
 * 系统版本：v1.0<br>
 * 开发人员： ganxiang20970 <br>
 * 开发时间：2018年04月18日 21:12<br>
 */
@ControllerAdvice
public class ExceptionConfig {

    //处理全局控制器抛出的tipException
    @ExceptionHandler(value = TipException.class)
    public ResponseEntity<?> tipExceptionHandler(TipException exception) {
        Map<String, Object> result = new HashMap<>();
        result.put("isSuccess", false);
        result.put("msg", exception.getMessage());
        return ResponseEntity.badRequest().body(result);
    }

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<?> exceptionHandler(Exception exception) {
        Map<String, Object> result = new HashMap<>();
        result.put("isSuccess", false);
        result.put("msg", exception.getMessage());
        return ResponseEntity.badRequest().body(result);
    }

    @ExceptionHandler(value = BindException.class)
    public ResponseEntity<?> validationExceptionHandler(BindException exception) {
        Map<String, Object> result = new HashMap<>();
        result.put("isSuccess", false);
        List<String> errors = exception.getAllErrors()
                .stream()
                .map(ObjectError::getDefaultMessage)
                .collect(Collectors.toList());
        result.put("msg", errors);
        return ResponseEntity.badRequest().body(result);
    }

    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) {
//        webDataBinder.setDisallowedFields("id"); 设置不允许的参数字段
    }
}
